import { _decorator, Component, EditBox, Button, Node, director } from "cc";
const { ccclass, property } = _decorator;
import { Session } from "@heroiclabs/nakama-js";
import { NakamaManager } from "./NakamaManager";

@ccclass("LobbyManager")
export class LobbyManager extends Component {
  @property(EditBox)
  roomCodeEditBox: EditBox = null;

  @property(Button)
  createButton: Button = null;

  @property(Button)
  joinButton: Button = null;

  private nakama = NakamaManager.getInstance();

  onLoad() {
    this.createButton.node.on(
      Button.EventType.CLICK,
      this.createPokerGame,
      this
    );
    this.joinButton.node.on(Button.EventType.CLICK, this.joinPokerGame, this);
  }

  async createPokerGame() {
    try {
      const matchId = await this.nakama.createPokerGame();
      console.log("游戏创建成功，房间代码:", matchId);
      await this.nakama.joinPokerGameWithMatchID(matchId);
      console.log("成功加入游戏，房间代码:", matchId);
      director.loadScene("poker");
    } catch (error) {
      console.error("创建游戏失败:", error);
    }
  }

  async joinPokerGame() {
    const roomCode = this.roomCodeEditBox.string.trim();
    if (!roomCode) {
      console.log("请输入房间代码");
      return;
    }
    try {
      await this.nakama.joinPokerGame(roomCode);
      director.loadScene("poker");
      console.log("成功加入游戏，房间代码:", roomCode);
    } catch (error) {
      console.error("创建游戏失败:", error);
    }
  }
}
